<template>
  <div class="project" v-loading="loading">
    <!-- 项目进度 -->
    <div class="project-part">
      <div class="project-part-title">项目进度</div>
      <el-button
        icon="el-icon-plus"
        class="add-button"
        @click="addProgress"
        >新增</el-button
      >
    </div>

    <el-row :gutter="20" align="middle" class="h-[48px]">
      <el-col :span="12">
        <div class="flex items-center h-full">
          <el-select
            v-model="year"
            placeholder="请选择"
            @change="changeYear"
            clearable
            class="w-full"
            style="height: 40px; line-height: 40px"
          >
            <el-option
              v-for="item in yearOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </div>
      </el-col>

      <el-col :span="6">
        <div
          class="flex items-center h-full"
          style="height: 40px; line-height: 40px"
        >
          <span class="mr-1 text-base"
            >本年度计划完成投资(万元)：</span
          >
          <span class="text-base">{{ planTotal }}</span>
        </div>
      </el-col>

      <el-col :span="6">
        <div
          class="flex items-center h-full"
          style="height: 40px; line-height: 40px"
        >
          <span class="mr-1 text-base"
            >本年度计划完成固投(万元)：</span
          >
          <span class="text-base">{{ fixedTotal }}</span>
        </div>
      </el-col>
    </el-row>

    <el-table
      class="project-table"
      :data="filteredProjectList"
      :header-cell-style="{
        background: '#F2F6FB',
        color: ' #6B767D'
      }"
    >
      <el-table-column label="年度" prop="year" width="100">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.year"
            placeholder="年度"
            clearable
            class="w-full"
            style="width: 80px"
            @change="
              validateYearMonth(scope.row, scope.$index)
            "
          >
            <el-option
              v-for="item in yearOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="月" prop="month" width="100">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.month"
            placeholder="月"
            clearable
            class="w-full"
            style="width: 80px"
            @change="
              validateYearMonth(scope.row, scope.$index)
            "
          >
            <el-option
              v-for="item in monthOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column
        label="本年度累计完成投资(万元)"
        prop="planTotalInvestment"
        width="120"
      >
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.planTotalInvestment"
            type="number"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="本年度累计完成固投(万元)"
        prop="fixedTotalInvestment"
        width="120"
      >
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.fixedTotalInvestment"
            type="number"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="累计完成投资(万元)"
        prop="totalInvestment"
        width="100"
      >
        <template slot-scope="scope">
          <div>
            {{
              setFinishInvest(scope.row.planTotalInvestment)
            }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="项目建设阶段"
        prop="projectStage"
      >
        <template slot-scope="scope">
          <el-select
            placeholder="请选择"
            v-model="scope.row.projectStage"
            clearable
          >
            <el-option
              v-for="item in projectBuildStageOptions"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column
        label="工程形象进度"
        prop="workProcess"
        width="300"
      >
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.workProcess"
            :ref="'textarea-' + scope.$index"
            type="textarea"
            rows="3"
            :autosize="true"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="是否应用统计库"
        prop="joinFlag"
      >
        <template slot-scope="scope">
          <el-radio-group v-model="scope.row.joinFlag">
            <el-radio label="是"></el-radio>
            <el-radio label="否"></el-radio>
          </el-radio-group>
        </template>
      </el-table-column>
      <el-table-column label="入库时间" prop="joinTime">
        <template slot-scope="scope">
          <el-date-picker
            v-model="scope.row.joinTime"
            type="date"
            :disabled="scope.row.joinFlag === '否'"
            style="width: 140px"
            placeholder="请选择"
          >
          </el-date-picker>
        </template>
      </el-table-column>
      <el-table-column label="进度图片" prop="imageList">
        <template slot-scope="scope">
          <div class="image-wrapper">
            <div
              v-for="(item, index) in scope.row.imageList"
              :key="index"
              class="image-container"
            >
              <el-image
                :src="item.src"
                class="progress-image"
                fit="contain"
                :preview-src-list="
                  scope.row.imageList.map((i) => i.src)
                "
                :initial-index="index"
              />
              <el-button
                type="danger"
                icon="el-icon-close"
                circle
                size="mini"
                @click="
                  handleDeleteImage(scope.$index, index)
                "
              ></el-button>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template slot-scope="scope">
          <div class="operation-wrapper">
            <el-upload
              action=""
              :auto-upload="false"
              :show-file-list="false"
              :on-change="
                (file, fileList) =>
                  handleUpload(
                    file,
                    scope.row,
                    scope.$index
                  )
              "
              multiple
            >
              <el-button type="text">上传</el-button>
            </el-upload>
            <el-button
              @click="deleteProgress(scope.$index)"
              type="text"
              style="color: #ff5b5b"
              >删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 推进节点 -->
    <div class="project-part">
      <div class="project-part-title">推进节点</div>
    </div>

    <div class="stage-list">
      <el-form :model="basicForm" label-position="top">
        <div
          v-for="(item, index) in stageList"
          :key="index"
          class="stage-item"
        >
          <div class="stage-header">
            <div class="circle-container">
              <div class="outer-circle active">
                <div class="inner-circle active"></div>
              </div>
            </div>
            <div class="stage-name">{{ item.node }}</div>
          </div>

          <el-row>
            <el-col :span="6">
              <el-form-item label="办理情况">
                <el-select
                  placeholder="请选择"
                  v-model="item.finishCondition"
                  clearable
                  style="width: 320px"
                  v-if="
                    item.node !== '开工' &&
                    item.node !== '竣工'
                  "
                  @change="
                    changeFinishCondition(item, index)
                  "
                >
                  <el-option
                    v-for="item in finishConditionOptions"
                    :key="item"
                    :label="item"
                    :value="item"
                  >
                  </el-option>
                </el-select>

                <el-select
                  placeholder="请选择"
                  v-model="item.finishCondition"
                  clearable
                  style="width: 320px"
                  v-else
                >
                  <el-option
                    v-for="item in isFinishOptions"
                    :key="item"
                    :label="item"
                    :value="item"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <template
              v-if="['开工', '竣工'].includes(item.node)"
            >
              <el-col :span="6">
                <el-form-item
                  v-if="item.finishCondition === '是'"
                  label="实际完成时间"
                >
                  <el-date-picker
                    v-model="item.realEndTime"
                    type="date"
                    placeholder="实际完成时间"
                    style="width: 320px"
                  >
                  </el-date-picker>
                </el-form-item>
                <el-form-item
                  v-if="item.finishCondition === '否'"
                  label="计划完成时间"
                >
                  <el-date-picker
                    v-model="item.planEndTime"
                    type="date"
                    placeholder="计划完成时间"
                    style="width: 320px"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </template>
            <template v-else>
              <el-col
                :span="6"
                v-if="
                  item.finishCondition === '未开始办理' ||
                  item.finishCondition === '办理中'
                "
              >
                <el-form-item label="计划开始时间">
                  <el-date-picker
                    v-model="item.planStartTime"
                    type="date"
                    placeholder="计划开始时间"
                    style="width: 320px"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col
                :span="6"
                v-if="
                  item.finishCondition === '未开始办理' ||
                  item.finishCondition === '办理中'
                "
              >
                <el-form-item label="计划完成时间">
                  <el-date-picker
                    v-model="item.planEndTime"
                    type="date"
                    placeholder="计划完成时间"
                    style="width: 320px"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col
                :span="6"
                v-if="item.finishCondition === '已办结'"
              >
                <el-form-item label="实际完成时间">
                  <el-date-picker
                    v-model="item.realEndTime"
                    type="date"
                    placeholder="实际完成时间"
                    style="width: 320px"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col
                :span="6"
                v-if="
                  item.finishCondition === '未开始办理' ||
                  item.finishCondition === '办理中'
                "
              >
                <el-form-item label="是否存在问题">
                  <el-select
                    placeholder="请选择"
                    v-model="item.problemFlag"
                    clearable
                    style="width: 320px"
                  >
                    <el-option
                      v-for="item in problemFlagOptions"
                      :key="item"
                      :label="item"
                      :value="item"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </template>
          </el-row>

          <el-row>
            <el-col
              :span="6"
              v-if="item.problemFlag === '是'"
            >
              <el-form-item label="问题描述">
                <el-input
                  style="width: 320px"
                  v-model="item.problemContent"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col
              :span="6"
              v-if="item.problemFlag === '是'"
            >
              <el-form-item label="解决措施">
                <el-input
                  style="width: 320px"
                  v-model="item.sloveMeasure"
                ></el-input>
              </el-form-item>
            </el-col>

            <!-- <el-col :span="6">
            <span>是否需要协调处理：</span>
            <span>{{ item.workFlag }}</span>
          </el-col> -->
          </el-row>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import {
  projectBuildStageOptions,
  finishConditionOptions
} from '@/utils/project/data'
import { uploadFileById } from '@/api/dataManagement'
import { STATIC_FILE_URL } from '@/api/config.js'

export default {
  props: {
    nodeList: Array,
    processList: Array,
    yearTotalList: Array,
    seasonTotalList: Array,
    isEdit: Boolean
  },
  data() {
    return {
      year: '',
      projectList: [],
      stageList: [
        {
          node: '可研评审',
          finishCondition: '',
          planStartTime: '',
          planEndTime: '',
          realEndTime: '',
          problemFlag: '',
          problemContent: '',
          sloveMeasure: ''
        },
        {
          node: '立项',
          finishCondition: '',
          planStartTime: '',
          planEndTime: '',
          realEndTime: '',
          problemFlag: '',
          problemContent: '',
          sloveMeasure: ''
        },
        {
          node: '土地报征批复',
          finishCondition: '',
          planStartTime: '',
          planEndTime: '',
          realEndTime: '',
          problemFlag: '',
          problemContent: '',
          sloveMeasure: ''
        },
        {
          node: '拆迁',
          finishCondition: '',
          planStartTime: '',
          planEndTime: '',
          realEndTime: '',
          problemFlag: '',
          problemContent: '',
          sloveMeasure: ''
        },
        {
          node: '签订出让合同',
          finishCondition: '',
          planStartTime: '',
          planEndTime: '',
          realEndTime: '',
          problemFlag: '',
          problemContent: '',
          sloveMeasure: ''
        },
        {
          node: '方案设计（规划审查）',
          finishCondition: '',
          planStartTime: '',
          planEndTime: '',
          realEndTime: '',
          problemFlag: '',
          problemContent: '',
          sloveMeasure: ''
        },
        {
          node: '施工图设计及审查',
          finishCondition: '',
          planStartTime: '',
          planEndTime: '',
          realEndTime: '',
          problemFlag: '',
          problemContent: '',
          sloveMeasure: ''
        },
        {
          node: '清单编制及评审',
          finishCondition: '',
          planStartTime: '',
          planEndTime: '',
          realEndTime: '',
          problemFlag: '',
          problemContent: '',
          sloveMeasure: ''
        },
        {
          node: '取得控制价批复并发布招标公告',
          finishCondition: '',
          planStartTime: '',
          planEndTime: '',
          realEndTime: '',
          problemFlag: '',
          problemContent: '',
          sloveMeasure: ''
        },
        {
          node: '评标结果公示',
          finishCondition: '',
          planStartTime: '',
          planEndTime: '',
          realEndTime: '',
          problemFlag: '',
          problemContent: '',
          sloveMeasure: ''
        },
        {
          node: '施工进场准备',
          finishCondition: '',
          planStartTime: '',
          planEndTime: '',
          realEndTime: '',
          problemFlag: '',
          problemContent: '',
          sloveMeasure: ''
        },
        {
          node: '开工',
          finishCondition: '',
          planStartTime: '',
          planEndTime: '',
          realEndTime: '',
          problemFlag: '',
          problemContent: '',
          sloveMeasure: ''
        },
        {
          node: '竣工',
          finishCondition: '',
          planStartTime: '',
          planEndTime: '',
          realEndTime: '',
          problemFlag: '',
          problemContent: '',
          sloveMeasure: ''
        }
      ],
      yearList: [],
      allProgressList: [],
      fileList: [],
      basicForm: {},
      problemFlagOptions: ['是', '否'],
      planTotal: '',
      fixedTotal: '',
      monthOptions: [],
      loading: false,
      isFinishOptions: ['是', '否'],
      isProcessInfoReady: false,
      isProcessInfoChanged: false
    }
  },
  computed: {
    projectBuildStageOptions() {
      return projectBuildStageOptions
    },
    finishConditionOptions() {
      return finishConditionOptions
    },
    filteredProjectList() {
      if (!this.year) return this.allProgressList
      return this.allProgressList.filter(
        (item) => item.year == this.year
      )
    }
  },
  watch: {
    processList: {
      handler(val) {
        if (this.isEdit) {
          // this.yearList = new Set(val.map((item) => item.year))

          this.allProgressList = val.map((item) => ({
            ...item,
            imageList: item.resourceFileInfos?.length
              ? item.resourceFileInfos.map((i) => ({
                  src: `${STATIC_FILE_URL}${i.filePath}`
                }))
              : []
          }))
          // this.projectList = JSON.parse(JSON.stringify(val))
          // if (this.year) {
          //   this.changeYear()
          // }
        }
      },
      deep: true,
      immediate: true
    },
    nodeList(val) {
      this.stageList = val
    },
    yearTotalList(val) {
      if (val.length > 0) {
        const curYear = new Date().getFullYear()
        console.log('curyear: ', curYear)
        const curYearRow = val.find(
          (e) => e.year == curYear
        )
        this.planTotal = curYearRow?.planTotal ?? ''
        // this.planTotal = val.filter(
        //   (i) => i.year == this.year
        // )
        //   ? val.filter((i) => i.year == this.year)[0]
        //       ?.planTotal
        //   : ''
      }
    },
    seasonTotalList(val) {
      if (val.length > 0) {
        const curYear = new Date().getFullYear()
        const curYearRow = val.find(
          (e) => e.year == curYear
        )
        this.fixedTotal = curYearRow?.fixedTotal ?? ''

        // this.fixedTotal = val.filter(
        //   (i) => i.year == this.year
        // )
        //   ? val.filter((i) => i.year == this.year)[0]
        //       ?.fixedTotal
        //   : ''
      }
    },
    filteredProjectList: {
      handler(val) {
        if (this.isProcessInfoReady === true) {
          this.isProcessInfoChanged = true
        }
      },
      deep: true
    },
    stageList: {
      handler(val) {
        if (this.isProcessInfoReady === true) {
          this.isProcessInfoChanged = true
        }
      },
      deep: true
    }
  },
  created() {
    const currentYear = new Date().getFullYear()
    this.yearOptions = Array.from(
      { length: 5 },
      (_, i) => currentYear - 4 + i
    ).sort((a, b) => b - a)
    for (let i = 1; i <= 12; i++) {
      this.monthOptions.push(i)
    }
  },
  methods: {
    setInfoReady() {
      setTimeout(() => {
        this.isProcessInfoReady = true
        this.isProcessInfoChanged = false
      }, 300)
    },
    addProgress() {
      this.year = ''
      this.allProgressList.push({
        year: '',
        month: '',
        planTotalInvestment: '',
        fixedTotalInvestment: '',
        planTotalInvestment: '',
        projectStage: '',
        workProcess: '',
        joinFlag: '否',
        joinTime: '',
        imageList: []
      })
      this.projectList = JSON.parse(
        JSON.stringify(this.allProgressList)
      )
      this.changeYear()
    },
    setFinishInvest(data) {
      const lastYear = Number(this.year) - 1
      const sum = this.allProgressList
        .filter((item) => item.year == lastYear)
        .reduce(
          (sum, item) =>
            sum +
            (parseFloat(item.planTotalInvestment) || 0),
          0
        )
      if (data) {
        return Number(sum) + Number(data)
      }
    },
    setMonth(month) {
      let monthList = []
      for (let i = 1; i <= month; i++) {
        monthList.push(i)
      }
      return monthList
    },
    changeYear() {
      this.year
        ? (this.projectList = this.allProgressList.filter(
            (i) => i.year == this.year
          ))
        : (this.projectList = this.allProgressList)
      if (this.yearTotalList.length > 0) {
        this.planTotal = this.yearTotalList.filter(
          (i) => i.year == this.year
        )
          ? this.yearTotalList.filter(
              (i) => i.year == this.year
            )[0]?.planTotal
          : ''
      }

      if (this.seasonTotalList.length > 0) {
        this.fixedTotal = this.seasonTotalList.filter(
          (i) => i.year == this.year
        )
          ? this.seasonTotalList.filter(
              (i) => i.year == this.year
            )[0]?.fixedTotal
          : ''
      }
    },
    tableCellClass() {
      return 'word-wrap'
    },
    handleUpload(file, row, index) {
      const reader = new FileReader()
      reader.onload = (e) => {
        const base64 = e.target.result
        const tempImage = { src: base64, uploading: true }
        this.allProgressList[index].imageList.push(
          tempImage
        )
      }
      reader.readAsDataURL(file.raw)

      const image = new FormData()
      image.append('file', file.raw)
      this.loading = true
      uploadFileById(image)
        .then((res) => {
          if (res.success) {
            const ids = res.data
            const oldValue =
              this.allProgressList[index].evidencePicture ||
              ''
            const combined = [
              ...new Set(
                (oldValue
                  ? oldValue.split(',')
                  : []
                ).concat(ids.split(','))
              )
            ]
            this.$set(
              this.allProgressList[index],
              'evidencePicture',
              combined.join(',')
            )
          }
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },

    handleDeleteImage(index, idx) {
      this.allProgressList[index].imageList.splice(idx, 1)
      const arr =
        this.allProgressList[index].evidencePicture.split(
          ','
        )
      arr.splice(idx, 1)
      this.$set(
        this.allProgressList[index],
        'evidencePicture',
        arr.join(',')
      )
    },

    getNodeList() {
      return this.stageList
    },
    getProcessList() {
      return this.allProgressList
    },
    deleteProgress(index) {
      this.allProgressList.splice(index, 1)
    },

    // 验证年月选择是否在上月及之前
    validateYearMonth(row, index) {
      // 只有在年度和月度都有值的情况下才进行验证
      if (row.year && row.month) {
        const selectedYear = parseInt(row.year)
        const selectedMonth = parseInt(row.month)

        // 获取当前日期
        const now = new Date()
        const currentYear = now.getFullYear()
        const currentMonth = now.getMonth() + 1 // getMonth() 返回 0-11，需要+1

        // 构建选择的日期（当月第一天）
        const selectedDate = new Date(
          selectedYear,
          selectedMonth - 1,
          1
        )
        // 构建当前月第一天
        const currentDate = new Date(
          currentYear,
          currentMonth - 1,
          1
        )

        // 如果选择的日期大于等于当前月，则不符合条件
        if (
          selectedDate.getTime() >= currentDate.getTime()
        ) {
          this.$message.warning('只能选择上月及之前的年月')
          // 清空年度和月度选择
          this.$set(this.allProgressList[index], 'year', '')
          this.$set(
            this.allProgressList[index],
            'month',
            ''
          )
        }
      }
    },
    changeFinishCondition(item, index) {
      Object.assign(this.stageList[index], {
        planStartTime: '',
        planEndTime: '',
        realEndTime: '',
        problemFlag: '',
        problemContent: '',
        sloveMeasure: ''
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/assets/css/form.scss';
.project {
  padding: 10px 10px 0 10px;
  position: relative;

  &-table {
    margin: 20px 0;
  }

  .add-button {
    position: absolute;
    left: 0;
    top: 0;
    width: 100px;
    height: 32px;
    background: #497fa3;
    border-radius: 4px;
    color: #fff;
    font-size: 14px;
    font-weight: 400;
    margin-left: 150px;
    margin-top: 15px;
  }
}

:v-deep(.el-select .el-input__suffix) {
  display: flex;
  align-items: center;
}

.deepshadow .el-select .el-input__suffix {
  display: flex;
  align-items: center;
}

::v-deep(.el-select .el-input__suffix) {
  display: flex;
  align-items: center;
}

.image-wrapper {
  display: flex;
  flex-wrap: nowrap;
  overflow-x: auto;
  max-width: 100%;
}

.image-container {
  position: relative;
  margin-right: 10px;
}

.progress-image {
  width: 100px;
  height: auto;
  flex-shrink: 0;
}

.image-container .el-button {
  position: absolute;
  top: 2px;
  right: 2px;
  padding: 2px;
}

.stage-list {
  padding: 10px;
}
.stage-item {
  padding: 10px 0;
}
.stage-header {
  display: flex;
  align-items: center;
}
.circle-container {
  margin-right: 10px;
}
.outer-circle {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  border: 1px solid #dcdfe6;
  display: flex;
  align-items: center;
  justify-content: center;
}
.outer-circle.active {
  /* border-color: rgba(0, 186, 255, 0.8); */
  background-color: rgba(0, 186, 255, 0.2);
}
.inner-circle {
  width: 10px;
  height: 10px;
  background-color: #dcdfe6;
  border-radius: 50%;
}
.inner-circle.active {
  background-color: rgba(0, 186, 255, 0.8);
}
.el-row {
  margin-top: 10px;
  color: #4b4c4d;
}

.word-wrap {
  white-space: normal;
  word-wrap: break-word;
  word-break: break-word;
}

.operation-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

::v-deep .el-input__inner {
  height: 32px !important;
}

::v-deep .el-form-item__label {
  margin-bottom: 0px !important;
}

::v-deep .el-form-item__content {
  margin-top: -15px !important;
}
</style>
